package dynamic.mybatisplus.core.toolkit;

import com.baomidou.mybatisplus.core.toolkit.Assert;

import com.github.yulichang.toolkit.MPJTableMapperHelper;
import dynamic.ibatis.session.DSqlSession;
import dynamic.mapper.DBaseMapper;
import dynamic.metadata.EntityClass;

import org.apache.ibatis.session.SqlSession;

import java.util.Map;
import java.util.Objects;

public class DSpringContentUtils {


    private static SpringContext springContext;

    public static void setSpringContext(SpringContext springContext) {
        if (Objects.isNull(DSpringContentUtils.springContext)) {
            DSpringContentUtils.springContext = springContext;
        }
    }

    public static <T> T getBean(Class<T> clazz) {
        return springContext.getBean(clazz);
    }

    @SuppressWarnings("UnusedReturnValue")
    public static <T> Map<String, T> getBeansOfType(Class<T> clazz) {
        return springContext.getBeansOfType(clazz);
    }

    @SuppressWarnings("unchecked")
    public static <T> T getMapper(EntityClass clazz) {
        if (Objects.isNull(springContext)) {
            DSqlSession session = DSqlHelper.sqlSession(clazz);
            Assert.notNull(session, "mapper not find by class <%s>", clazz.getSimpleName());
            DBaseMapper mapper = DSqlHelper.getMapper(clazz, session);
            Assert.notNull(mapper, "mapper not find by class <%s>", clazz.getSimpleName());
            return (T) mapper;
        }
        Class<?> mapper = DMPJTableMapperHelper.getMapper(clazz);
        Assert.notNull(mapper, "mapper not find by class <%s>", clazz.getSimpleName());
        Object bean = getBean(mapper);
        Assert.notNull(bean, "mapper not find by class <%s>", clazz.getSimpleName());
        return (T) bean;
    }

    public interface SpringContext {

        <T> T getBean(Class<T> clazz);

        <T> Map<String, T> getBeansOfType(Class<T> clazz);
    }
}
